package net.adetech.crj.utils.job;

import com.jfinal.kit.PropKit;
import net.adetech.crj.controller.CrjController;
import net.adetech.crj.utils.SerializeUtil;
import net.adetech.crj.utils.ServiceUtil;
import net.adetech.crj.utils.entity.ServiceResponse;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

public class ScanFtpJob implements Runnable{


    static String ftpIp = PropKit.get("ftp_in2out_ip");
    static int ftpPort = PropKit.getInt("ftp_in2out_port");
    static String path = PropKit.get("ftp_in2out_path");
    static String ftpUsername = PropKit.get("ftp_in2out_username");
    static String ftpPassword = PropKit.get("ftp_in2out_password");
    static String ftpLocalPath = PropKit.get("ftp_in2out_localpath");

    @Override
    public void run() {
        FTPClient ftp = new FTPClient();
        String time1 = new SimpleDateFormat("HH:mm:ss SSS").format(new Date());
        try {
            ftp.connect(ftpIp,ftpPort);
//            System.out.println("Connected to " + ftpIp + ".");
//            System.out.print(ftp.getReplyString());
            //ftp.enterLocalPassiveMode();
            ftp.login(ftpUsername,ftpPassword);
            ftp.changeWorkingDirectory(path);
            FTPFile[] ftpFiles = ftp.listFiles();
            List<String> tempFilePathList = new ArrayList<String>();
            for (FTPFile ftpFile:ftpFiles) {
                if (ftpFile.isFile())
                {
                    String tempLocalFilePath = ftpLocalPath+ftpFile.getName();
                    ftp.retrieveFile(ftpFile.getName(),new FileOutputStream(tempLocalFilePath));
                    ftp.deleteFile(ftpFile.getName());
                    tempFilePathList.add(tempLocalFilePath);
                }
            }
            this.ftpClose(ftp);

            for (String tempLocalFilePath:tempFilePathList
                 ) {
                this.handleFile(tempLocalFilePath);
            }


        } catch (Exception e) {
            e.printStackTrace();
            //this.ftpClose(ftp);
        }
        String time2 = new SimpleDateFormat("HH:mm:ss SSS").format(new Date());

        //System.out.println(time1+" ----> "+time2);

    }

    private void handleFile(String path)
    {
        SAXReader reader = new SAXReader();
        try {
            Document document = reader.read(new File(path));
            Element root = document.getRootElement();
            String rootName = root.getName();
            if ("response".equals(rootName))
            {
                String responseString = root.getText();

                ServiceResponse response = (ServiceResponse) SerializeUtil.stringToObject(responseString);
                String uuid = response.getServiceId();
                ServiceUtil.setResponse(uuid,response);
            }
            else if("request".equals(rootName))
            {
                String requestString = root.getText();
                requestString = SerializeUtil.decodeBase64(requestString);
                String method = requestString.split(":")[0];
                String[] params = requestString.split(":")[1].split(",");
                if ("submitTable".equals(method))
                {
                    String idType = params[0];
                    String idNumber = params[1];
                    String realName = params[2];
                    String clientNo = params[3];
                    System.out.println("完成号码:"+idNumber);
                    CrjController.submitTable(idNumber,clientNo);
                }

            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private void ftpClose(FTPClient ftp) {
        try {
            ftp.logout();
            if (ftp.isConnected()) {
                ftp.disconnect();
            }
        } catch (IOException e) {
            e.printStackTrace();
            System.exit(1);
        }
    }
}
